package cn.wangkai.peanut.util.msg;

import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.wangkai.peanut.db.MyDb;
import cn.wangkai.peanut.db.WKDbException;
import cn.wangkai.peanut.db.iface.IMyDb;
import cn.wangkai.peanut.mvc.admin.dao.manager.UserManager;
import cn.wangkai.peanut.mvc.admin.dao.manager.UserManagerImp;
import cn.wangkai.peanut.mvc.admin.model.User;
import cn.wangkai.peanut.system.db.PeanutDb;

public class Generate {

	private static UserManager userManager = new UserManagerImp();
	public static Pattern referer_pattern = Pattern.compile("@([^@^\\s^:]{1,})([\\s\\:\\,\\;]{0,1})");//@.+?[\\s:]
	private static PeanutDb db = PeanutDb.Open();
	/**
	 * 处理提到某人 @xxxx
	 * @param msg  传入的文本内容
	 * @param referers 传出被引用到的会员名单
	 * @return 返回带有链接的文本内容
	 * @throws SQLException 
	 */
	public static String _GenerateRefererLinks(String msg, List<String> referers) throws SQLException {
		IMyDb myDb = MyDb.Open(db);
		try{
		    StringBuilder html = new StringBuilder();
		    int lastIdx = 0;
		    Matcher matchr = referer_pattern.matcher(msg);
		    while (matchr.find()) {
		        String origion_str = matchr.group();
		        String username = origion_str.substring(1, origion_str.length()).trim();
		        html.append(msg.substring(lastIdx, matchr.start()));
		         
		        User u = userManager.findUserByName(myDb,username);//根据用户名获取用户
		         
		        if(u != null){
		            html.append("<a href='javascript:remsg(\""+u.getUsername()+"\");' class='referer'>@");
		            html.append(username.trim());
		            html.append("</a> ");
		            if(referers != null && !referers.contains(u.getUserid()))
		                referers.add(u.getUserid());
		        } else{
		            html.append(origion_str);
		        }
		        lastIdx = matchr.end();
		    }
		    html.append(msg.substring(lastIdx));
		    return html.toString();
		} catch (WKDbException e) {
			return msg;
		}finally{
			myDb.Close();
		}
	}
	
	public static void main(String[] args) {
	}
}
